<!--
 * @Author: zhangduo 445629906@qq.com
 * @Date: 2023-12-10 22:19:23
 * @LastEditors: zhangduo 445629906@qq.com
 * @LastEditTime: 2023-12-11 03:49:58
 * @FilePath: \mdbj-ui\src\views\mypage\roadinspection\dataPanel.vue
 * @Description: 巡查记录管理数据列表主界面，展示全部道路信息
 * 
 * Copyright (c) 2023 by zhangduo, All Rights Reserved. 
-->
<template>
  <div>
    <el-row>
      <el-col :span="24" class="title-row">
        <span>| 巡查记录管理</span>
      </el-col>
    </el-row>
    <div v-show="true">
      <div style="display: flex; justify-content: space-between">
        <el-switch
          v-model="showSearch"
          style="height: 33px"
          active-text="查询条件"
          active-color="#13ce66"
          @change="switchChange"
        >
        </el-switch>
      </div>
      <el-form
        ref="form"
        :model="queryParams"
        label-width="80px"
        size="small"
        :inline="true"
        v-show="showSearch"
        class="queryPanel"
      >
        <el-form-item label="道路名称">
          <el-input v-model="queryParams.name" style="width: 10vw"></el-input>
        </el-form-item>
        <!-- <el-form-item label="标识码">
              <el-input
                v-model="queryParams.objcode"
                style="width: 10vw"
              ></el-input>
            </el-form-item> -->

        <el-form-item label="道路等级">
          <el-select
            v-model="queryParams.roadclass_js"
            placeholder="请选择树种"
            style="width: 10vw"
            clearable
            @change="handleChangeRoadClass"
          >
            <el-option
              v-for="dict in dict.type.sys_roadclass_js"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="保洁公司">
          <el-select
            v-model="queryParams.cleancompany"
            placeholder="请选择保洁公司"
            style="width: 10vw"
            clearable
            @change="handleChangeCleanCompany"
          >
            <el-option
              v-for="dict in dict.type.sys_cleancompany"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="空间范围" size="normal">
          <el-button type="info" size="mini" @click="drawExtent('rectangle')"
            >矩形</el-button
          >
          <el-button type="info" size="mini" @click="drawExtent('polygon')"
            >多边形</el-button
          >
        </el-form-item>
      </el-form>
      <el-row :gutter="20" style="text-align: center" v-show="showSearch">
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >查询</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-row>

      <el-table
        :data="features"
        v-loading="loading"
        element-loading-text="正在加载中"
        stripes
        highlight-current-row
        :height="tableHeight"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="objectid"
          align="center"
          prop="attributes.objectid"
          width="70"
        />
        <el-table-column
          label="名称"
          align="center"
          :show-overflow-tooltip="true"
          prop="attributes.name"
        ></el-table-column>
        <el-table-column
          label="道路等级"
          width="80"
          align="center"
          :show-overflow-tooltip="true"
          prop="attributes.roadclass_js"
        >
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.sys_roadclass_js"
              :value="scope.row.attributes.roadclass_js"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="保洁单位"
          align="center"
          :show-overflow-tooltip="true"
          prop="attributes.cleancompany"
        >
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleView(scope.row, scope.index)"
              >查看记录</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleAdd(scope.row)"
              v-hasPermi="['datamanager:gusmm:edit']"
              >新增记录</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-location-outline"
              @click="handleLocate(scope.row, scope.index)"
              >定位</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        layout="total, sizes,prev, pager, next"
        @pagination="getList"
      />
    </div>
  </div>
</template>

<script>
import FeatureLayer from "@arcgis/core/layers/FeatureLayer";
export default {
  props: {
    mapview: { default: () => {} },
  },
  dicts: ["sys_roadclass_js", "sys_cleancompany"],
  components: {},
  inject: ["toggleComponent"],
  data() {
    return {
      paramObj: {},
      split1: 0.5,
      // 表格高度
      tableHeight: "75vh",
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: false,
      // 选中数组
      ids: [],
      // 选中的要素
      selectFeatures: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        name: undefined,
        roadclass_js: undefined,
        cleancompany: undefined,
        geometry: null,
      },
      // 要素图层url
      featureLayerUrl:
        window.mapConfig.operationLayers.featurelayers["roadlayer"].url,
      //定位级别
      zoomLevel:
        window.mapConfig.operationLayers.mapservers["roadlayer"].zoomLevel,
      // 概略查询字段
      outFields:
        window.mapConfig.operationLayers.mapservers["roadlayer"].outFields,
      // 空间查询选中符号
      selectSymbol:
        window.mapConfig.operationLayers.mapservers["roadlayer"].symbol,
      // 定位符号
      locateSymbol:
        window.mapConfig.operationLayers.mapservers["roadlayer"].symbol,
      // 框选范围的符号
      selectExtentSymbol: window.mapConfig.symbols.selectExtent,
      // 要素图层
      featureLayer: undefined,
      // 图层视图
      layerView: undefined,
      highlight: undefined,
      selectedGraphic: null,
      // 查询范围
      queryExtent: null,
      // 属性查询条件
      whereClause: undefined,
      // 当前页要素集合
      features: [],
      homeViewpoint: undefined,
    };
  },
  created() {
    let _self = this;
    _self.xzqhOptions = city;
    _self.typesOptions = types;
  },
  mounted() {},

  // activated​ 若组件实例是 <KeepAlive> 缓存树的一部分，当组件被插入到 DOM 中时调用。
  activated() {
    if (this.featureLayer == undefined) {
      this.initFeatureLayer();
      return;
    }
    this.getList();
  },

  methods: {
    /**
     * @description: 切换查询面板显示隐藏
     * @param {*} val
     * @return {*}
     */
    switchChange(val) {
      console.log(val);
      if (val) {
        this.tableHeight = "65vh";
      } else this.tableHeight = "75vh";
    },

    /**
     * @description: 查询按钮
     * @return {*}
     */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /**
     * @description: 初始化featurelayer
     * @return {*}
     */
    initFeatureLayer() {
      let _self = this;
      _self.featureLayer = new FeatureLayer({
        title: "道路中心线",
        url: this.featureLayerUrl,
        outFields: ["objectid"],
        // renderer: this.createRenderer(),
      });
      // _self.mapview.map.add(_self.featureLayer);
      _self.mapview.map.addMany([_self.featureLayer]);
      _self.featureLayer
        .when(() => {
          return _self.featureLayer.queryExtent();
        })
        .then((response) => {
          _self.mapview.goTo(response.extent.expand(0.7));
          // 初始范围
          _self.homeViewpoint = response.extent.expand(0.7); //_self.mapview.viewpoint.clone();
        });

      _self.mapview.whenLayerView(_self.featureLayer).then((layerView) => {
        console.log(layerView);
        _self.layerView = layerView;
        this.getList();
      }); // Get the screen point from the view's click event
      _self.mapview.on("click", function (event) {
        // Search for graphics at the clicked location. View events can be used
        // as screen locations as they expose an x,y coordinate that conforms
        // to the ScreenPoint definition.
        _self.mapview.hitTest(event).then(async function (response) {
          if (response.results.length) {
            let graphic = response.results.filter(function (result) {
              // check if the graphic belongs to the layer of interest
              return result.graphic.layer === _self.featureLayer;
            })[0].graphic;
            _self.handleLocate(graphic, true);
            let queryParams = {
              outFields: ["*"],
              where: `objectid=${graphic.attributes["objectid"]}`,
              returnGeometry: true,
            };
            const featureSet = await _self.featureLayer.queryFeatures(
              queryParams
            );
            const feature = featureSet.features[0];

            let paramObj = {
              feature: feature,
              featureLayer: _self.featureLayer,
              selectedGraphic: _self.selectedGraphic,
            };
            _self.toggleComponent("roadDetailPanel", paramObj);
          }
        });
      });
    },

    /**
     * @description: 根据查询参数构建where查询条件
     * @return {*}
     */
    getWhereClause() {
      let _self = this;
      //   queryParams
      let whereClause = "1=1";
      if (_self.queryParams.name)
        whereClause += " and name like '%" + _self.queryParams.name + "%'";
      if (_self.queryParams.roadclass_js)
        whereClause +=
          " and roadclass_js = '" + _self.queryParams.roadclass_js + "'";
      if (_self.queryParams.cleancompany)
        whereClause +=
          " and cleancompany like '%" + _self.queryParams.cleancompany + "%'";
      return whereClause;
    },

    /**
     * @description: 重置查询条件
     * @return {*}
     */
    resetQueryParams() {
      let _self = this;
      _self.queryParams.name = null;
      _self.queryParams.roadclass_js = null;
      _self.queryParams.cleancompany = null;
      _self.selectedGraphic = null;
      _self.whereClause = null;
      _self.queryExtent = null;
    },

    /**
     * @description: 调用arcgis js api查询数据
     * @return {*}
     */
    getList() {
      let _self = this;
      _self.loading = true;
      _self.whereClause = _self.getWhereClause();
      // 先构建用于查询数据总条数的查询参数对象
      let queryParams = {
        // 空间查询方式，相交查询
        spatialRelationship: "intersects",
        // 空间查询范围
        geometry: _self.queryExtent == null ? null : _self.queryExtent.geometry, // 草绘要素几何
        // 输出字段
        outFields: ["objectid"],
        where: _self.whereClause,
      };
      // 首先查询数据总条数用于渲染分页组件值
      _self.featureLayer.queryFeatureCount(queryParams).then((numResults) => {
        _self.total = numResults;
      });

      // 高亮显示选定空间范围内的数据
      if (_self.queryExtent != null) {
        queryParams = { returnGeometry: true, ...queryParams };
        _self.featureLayer.queryFeatures(queryParams).then((featureSet) => {
          // featureSet.features.map((feature) => {
          //   feature.symbol =
          //     window.mapConfig.operationLayers.mapservers["dianzld"].symbol;
          //   // feature.popupTemplate = popupTemplate;
          //   return feature;
          // });
          // 将要素添加至图形图层
          // _self.mapview.graphics.addMany(featureSet.features);
          _self.mapview.goTo(_self.queryExtent);
          // 移除当前高亮图形
          _self.highlight?.remove();
          // 高亮显示当前页要素
          _self.highlight = _self.layerView.highlight(featureSet.features);
        });
      }
      // 分页查询并在表格展示数据
      queryParams = {
        spatialRelationship: "intersects",
        geometry: _self.queryExtent == null ? null : _self.queryExtent.geometry, // 草绘要素几何
        start: (_self.queryParams.pageNum - 1) * _self.queryParams.pageSize,
        num: _self.queryParams.pageSize,
        outFields: ["objectid", "name", "code", "roadclass_js", "cleancompany"],
        returnGeometry: false,
        orderByFields: ["objectid"],
        where: _self.whereClause,
      };
      // 查询数据
      _self.featureLayer.queryFeatures(queryParams).then((featureSet) => {
        _self.features = featureSet.features;
        _self.loading = false;
      });
    },

    /**
     * @description: 详细按钮操作
     * @param {*} row 按钮所在数据行
     * @return {*}
     */
    async handleView(row) {
      let paramObj = {
        roadcode: row.attributes["code"],
        roadname: row.attributes["name"],
      };
      this.toggleComponent("inceptionDataPanel", paramObj);
    },
    /**
     * @description: 修改按钮
     * @param {*} row 按钮所在数据行
     * @return {*}
     */
    async handleUpdate(row) {
      let _self = this;
      if (row == null && _self.selectFeatures.length != 0)
        row = _self.selectFeatures[0];
      _self.handleLocate(row, false);

      console.log(row);
      let queryParams = {
        outFields: ["*"],
        where: `objectid=${row.attributes["objectid"]}`,
        returnGeometry: true,
      };
      const featureSet = await _self.featureLayer.queryFeatures(queryParams);
      const feature = featureSet.features[0];
      let paramObj = {
        feature: feature,
        featureLayer: this.featureLayer,
      };
      // 切换编辑面板
      this.toggleComponent("roadEditPanel", paramObj);
    },
    /**
     * @description: 新增按钮
     * @return {*}
     */
    handleAdd(row) {
      let _self = this;
      let paramObj = {
        roadcode: row.attributes["code"],
        roadname: row.attributes["name"],
      };
      this.toggleComponent("inceptionAddPanel", paramObj);
    },
    /**
     * @description: 删除按钮
     * @return {*}
     */
    handleDelete(row) {
      let _self = this;
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const deleteFeatures =
            row == null && _self.selectFeatures.length != 0
              ? _self.selectFeatures
              : [row];
          const edits = {
            deleteFeatures: deleteFeatures,
          };
          // 删除要素
          _self.featureLayer.applyEdits(edits).then((editsResult) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            console.log(editsResult);
            _self.getList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    /**
     * @description: 导出数据
     * @param {*} row 选中的数据行
     * @return {*}
     */
    handleExport(row) {
      let _self = this;
      const exportFeatures =
        row == null && _self.selectFeatures.length != 0
          ? _self.selectFeatures
          : [row];
      _self.queryParams.objectids = exportFeatures.map((feature) => {
        return feature.attributes.objectid;
      });
      this.downloadNode(
        "green/dataManager/gusmm/exportData",
        {
          ..._self.queryParams,
        },
        `古树名木_${new Date().getTime()}.xlsx`
      );
    },

    /**
     * @description: 定位按钮操作
     * @param {*} row
     * @return {*}
     */
    async handleLocate(row) {
      let _self = this;
      let queryParams = {
        outFields: ["*"],
        where: `objectid=${row.attributes["objectid"]}`,
        returnGeometry: true,
      };
      const featureSet = await _self.featureLayer.queryFeatures(queryParams);
      const feature = featureSet.features[0];
      // 移除前一个高亮图形
      _self.highlight?.remove();
      // 高亮显示当前页要素;
      _self.highlight = _self.layerView.highlight(featureSet.features);
      if (feature.geometry == null) {
        _self.$message.error("暂无空间信息");
        return;
      }
      _self.mapview
        .goTo({
          target: feature.geometry,
          zoom: _self.zoomLevel,
        })
        .catch((error) => {
          if (error.name != "AbortError") {
            console.error(error);
          }
        });
    },
    /**
     * @description: 多选框选中数据
     * @param {*} selection 选中的行
     * @return {*}
     */
    handleSelectionChange(selection) {
      // this.ids = selection.map((item) => item.attributes.objectid);
      this.selectFeatures = selection;
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /**
     * @description: 绿地类型选择事件
     * @param {*} value
     * @return {*}
     */
    handleChangeRoadClass(value) {
      console.log(value);
      this.queryParams.roadclass_js = value;
      this.handleQuery();
    },
    /**
     * @description: 树种选择事件
     * @return {*}
     */
    handleChangeCleanCompany(value) {
      console.log(value);
      this.queryParams.cleancompany = value;
      this.handleQuery();
    },
    //
    /**
     * @description: 绘制查询范围
     * @param {*} drawType 图形类型，rectangle or polygon
     * @return {*}
     */
    drawExtent(drawType) {
      let _self = this;
      _self.clearGraphics();
      // 添加草绘微件
      const graphicsLayerSketch = new GraphicsLayer();
      const sketchViewModel = new SketchViewModel({
        id: drawType,
        view: _self.mapview,
        layer: graphicsLayerSketch,
        polygonSymbol: window.mapConfig.symbols.selectExtent,
      });
      sketchViewModel.on("create", (event) => {
        if (event.state === "complete") {
          console.log("Sketch complete");
          // 地图上添加绘制范围
          _self.mapview.graphics.add(event.graphic);
          _self.queryExtent = event.graphic;
        }
      });
      sketchViewModel.create(drawType);
    },

    /**
     * @description: 重置按钮操作
     * @return {*}
     */
    resetQuery() {
      this.resetForm("queryForm");
      this.resetQueryParams();
      this.handleQuery();
      this.clearGraphics();
      this.mapview.goTo(this.homeViewpoint);
    },
    /**
     * @description: 清除临时图形
     * @return {*}
     */
    clearGraphics() {
      let _self = this;
      _self.mapview.popup.close();
      _self.mapview.graphics.removeAll();
      if (_self.highlight) {
        _self.highlight.remove();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  height: calc(100vh - 60px);
}

.map-container {
  padding: 0;
  margin: 0;
  width: 100%;
  height: calc(100vh - 60px);
}

.title-row {
  width: 100%;
  font-size: 18px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 1vh;
}

#idSplitInfoTitle {
  font-size: 18px !important;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: rgba(51, 51, 51, 1);
  padding: 0px 0px 0px 8px !important;
  //margin-left: 16px;
  border-left: 2px solid #008a96;
  margin-top: 10px;
  //position: absolute;
  z-index: 1;
}

.leftPanel {
  height: calc(100vh - 60px);
}

.rightPanel {
  height: calc(100vh - 60px);
  padding: 10px;

  .queryPanel {
    display: flex;
    flex-wrap: wrap;
  }
}
::v-deep .el-form-item {
  margin-bottom: 0px !important;
}

::v-deep .pagination-container {
  padding: 16px 16px !important;
}
.chartPanel {
  width: 100%;
  height: calc(100vh - 60px);
}
</style>
